<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/5/27
 * Time: 19:06
 */

namespace app\admin\logic;


use app\admin\logic\code\ErrorCode;
use app\common\model\Region;

class RegionLogic extends BaseLogic
{

    private $regionModel;

    public function __construct()
    {
        parent::__construct();
        $this->regionModel = new Region();
    }

    /**
     * 地区列表
     * @param $parentId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function regionList($parentId){
        $where[] = ['parent_id', '=', $parentId];
        $regionList = Region::where($where)->field('id,name AS title,parent_id AS parentId')->select();
        foreach ($regionList as $key=>$val){
//            $regionList[$key]->children = [''];
            $childWhere = [];
            $childWhere[] = ['parent_id', '=', $val->id];
            $childreList = Region::where($childWhere)->field('id,name AS title,parent_id AS parentId')->select();
            if (count($childreList)>0){
//                $childreList = json_decode(json_encode($childreList), true);
                $regionList[$key]->children = [""];
            }
        }
        return ajaxArr(ErrorCode::$SUCCESS, 'success', $regionList);
    }

    /**
     * 处理逻辑
     * @param $data
     */
    public function handle($data){
        $act = $data['act'];
        unset($data['act']);
        $res = false;
        $resData = [];
        switch ($act){
            case 'add':
                $this->regionModel->name = $data['context'];
                $this->regionModel->level = $data['level'];
                $this->regionModel->parent_id = $data['parentId'];
                $res = $this->regionModel->save();
                break;
            case 'edit':
                $region = $this->regionModel->get($data['nodeId']);
                $region->name = $data['context'];
                $res = $region->save();
                break;
            case 'del':
                $region = $this->regionModel->get($data['nodeId']);
                $res = $region->delete();
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功', $resData);
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

}